<?php
namespace Admin\Controller;
use Think\Controller;
class TwoSortController extends CommonController {

	public function _initialize(){
		parent::_initialize();
	}
	//显示商品二级分类信息列表
	public function manageTwoSort(){
		$sort_id = I("get.sort_id");
		if (!empty($sort_id)) {
			$Sort = M("Sort");
			$sortname=$Sort->where("id={$sort_id}")->getField("sortname");
			$this->assign("sortname",$sortname);
		}		
		$this->display("managetwosort");
	}


	//显示添加二级商品分类界面
	public function newTwoSort(){
		$Sort = M("Sort");
		$sort_id = I("get.sort_id");
		if (!empty($sort_id)) {
			$Sortdata=$Sort->where("id={$sort_id}")->find();
			$this->assign("OneSort",$Sortdata);
		}else{
			$Sortdata=$Sort->order("id asc")->select();
			$this->assign("OneSortlist",$Sortdata);
		}
		
	       	$this->display("addtwosort");
	}

	//显示编辑一级商品分类界面
	public function editTwoSort(){
		$twosort_id = I("get.twosort_id");
		$TwoSort = M('Twosort');
		$TwoSortdata = $TwoSort->where("id ={$twosort_id} ")->find();
		$Sort = M("Sort");
		$Sortdata = $Sort->where("id ={$TwoSortdata['sortid']}")->find();
		$TwoSortdata['twosortimgurl'] = json_decode($TwoSortdata['twosortimgurl'],true);
		$TwoSortdata['twosortimgurl'] = $TwoSortdata['twosortimgurl'] [0];
		$TwoSortdata['sortname'] = $Sortdata['sortname'];
		//用于判断是否是编辑商品分类信息
		$this->assign("twosorttag",$twosort_id);
		$this->assign("TwoSortdata",$TwoSortdata);
		$this->display("addtwosort");
	}

	//保存编辑后的二级商品分类信息
	public function savetwosort(){
		$TwoSort = M('Twosort');
		$checkrules = array(
 			array('twosortname','require','商品分类名称必须填写！'), // 商品分类名称必须
 			//array('sortname','','商品分类已经存在！',1,'unique',1), // 验证商品分类是否已经存在
			array('createdate','require','发布时间必须填写！'), // 修改时间必须
		);
		$data=$TwoSort ->validate($checkrules)->create();
		if (!$data) {
			$this->error($TwoSort->getError());
		}else{
			$twosortimgurl=I('post.imgs','','');
			if (empty($twosortimgurl)) {
				$this->error("请上传分类图标！");
			}else{
				$data['twosortimgurl']  =  json_encode($twosortimgurl);
				//判断是否是添加新分类或者编辑分类
				$twosort_id = I("get.twosort_id");

				if (empty($twosort_id)) {
					$ret=$TwoSort->where("twosortname ='{$data['twosortname']}' ")->find();
					if ($ret) {
						$this->error("商品分类已经存在！");
					}else{
						$res=$TwoSort->add($data);
					}
				}else{
					$res = $TwoSort->where("id ={$twosort_id}")->save($data);
				}
				if (!$res) {
					$this->error("请确认商品二级分类信息是否填写正确！");
				}else{
					$this->success("保存商品二级分类信息成功！");
				}				
			}		
		}
	}
	//删除二级分类
	public function delTwoSort(){
		$twosortid = I("get.twosort_id");
		$TwoSort = M('Twosort');
		$res=$TwoSort->where("id ={$twosortid}")->delete();
		if ($res) {
			$this->success("删除二级分类成功！");
		}else{
			$this->error("删除二级分类失败！");
		}
	}
	
}